/**
 * File: FilterSequences.java
 * Created by: mhaimel
 * Created on: 23 Jun 2009
 * CVS:  $Id: FilterSequences.java,v 1.1 2009/11/24 16:24:00 mhaimel Exp $
 */
package uk.ac.ebi.curtain.exec;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.data.FileType;
import uk.ac.ebi.curtain.utils.data.ReadType;
import uk.ac.ebi.curtain.utils.file.EntryMapper;
import uk.ac.ebi.curtain.utils.file.EntryMapperBean;
import uk.ac.ebi.curtain.utils.file.FileInfo;
import uk.ac.ebi.curtain.utils.io.impl.FileIO;

/**
 * @author mhaimel
 *
 */
public class FilterSequences {
	
	public static void main(String[] args) {
		final AtomicInteger limit = new AtomicInteger(100);
		final AtomicReference<PrintWriter> out = new AtomicReference<PrintWriter>();
		out.set(new PrintWriter(new OutputStreamWriter(System.out)));
		int i = 0;
		try{
			while (i < args.length && args[i].startsWith("-")) {
				if (args[i].equals("-h") || args[i].equals("-help")
						|| args[i].equals("--help")) {
					System.out.println("-l\tSequence cutoff length, default:100");
					System.out.println("-o\tOutput file, default:stdout");
					++i;
					System.exit(1);
				} else if (args[i].equals("-l")) {
					++i;
					limit.set(Integer.valueOf(args[i++]));
				} else if (args[i].equals("-o")) {
					out.set(new FileIO(new File(args[++i])).getPrintWriter());
					++i;
				}
			}
			

			while(i < args.length){
				String in = args[i++];				
				FileInfo fi = new FileInfo(in,FileType.fasta,ReadType.Contig);
				fi.getFileType().getParser().parse(fi, new EntryMapper(){
	
					@Override
					public void mapEntry(EntryMapperBean bean) {
						if(bean.getSequence().length() >= limit.get()){
							FileType.fasta.getWriter().write(out.get(), bean);
						}
					}}
				);
			}			
		} catch (FileNotFoundException e) {
			throw new CurtainUncheckedException("Not able to write results to " + args[i]);
		} catch (IOException e) {
			throw new CurtainUncheckedException("Not able to write results to " + args[i]);
		} finally{
			FileIO.closeQuietly(out.getAndSet(null));
		}
		
	}
}
